<?php
namespace app\index\controller;

use app\index\Controller;
use app\index\Model\User as UserModel;
use think\Db;
use think\Hook;
use think\Session;

class User extends Controller
{
    //初始化
    public function _initialize()
    {
        parent::_initialize();
    }

    //用户首页
    public function index()
    {
        $this->checkAgentInfo();
        $tag  = $this->security();
        $msgs = Db::name('user_msg')
            ->where('receive_user_id', $this->user['id'])
            ->where('is_delete', 0)
            ->order('id desc')->paginate(5);
        $mainCount = Db::name('main_account')->where(['user_id' => $this->user['id'], 'status' => 1])->count();
        $sonCount  = Db::name('son_account')->where(['user_id' => $this->user['id'], 'status' => 1])->sum('num');
        $dayPrice  = Db::name('day_record')->where('date', strtotime(date("Y-m-d")))->value('price');
        $this->assign('currency', config('currency'));
        $this->assign('msgs', $msgs);
        $this->assign('tag', $tag);
        $this->assign('mainCount', $mainCount);
        $this->assign('sonCount', $sonCount);
        $this->assign('dayPrice', $dayPrice);
        return $this->fetch();
    }

    //检查代理信息
    private function checkAgentInfo()
    {
        if ($this->user['agent']) {
            if (
                empty($this->user['realname']) ||
                empty($this->user['alipay']) ||
                empty($this->user['bank']) ||
                empty($this->user['bank_card'])
            ) {
                $this->error('请先完善所有基本信息。', 'index/user/info');
            }
        }
        return true;
    }

    //获取帐户安全级别
    private function security()
    {
        $level = 0;
        if ($this->user) {
            if (!empty($this->user['mobile'])) {
                $level++;
            }
            if (!empty($this->user['email'])) {
                $level++;
            }
            if (!empty($this->user['identity']) && !empty($this->user['password2'])) {
                $level++;
            }
        }
        $tag = array();
        switch ($level) {
            case '1':
                $tag['level']    = 1;
                $tag['text']     = '低';
                $tag['progress'] = '40';
                break;
            case '2':
                $tag['level']    = 2;
                $tag['text']     = '中';
                $tag['progress'] = '70';
                break;
            case '3':
                $tag['level']    = 3;
                $tag['text']     = '高';
                $tag['progress'] = '100';
                break;
        }
        return $tag;
    }

    //用户注册
    public function register()
    {
        if ($this->request->isAjax()) {
            $input = $this->request->post();

            $result = $this->validate($input, 'User.addUser');

            if ($result !== true) {
                return json(['success' => 0, 'msg' => $result]);
            }

            if ($this->verifyToken($input['__token__']) === false) {
                return json(['success' => 0, 'msg' => '令牌错误']);
            }

            if (Session::get('mobile_code') != $input['code']) {
                return json(['success' => 0, 'msg' => '短信验证码错误']);
            }

            if (UserModel::get($input['invite'])) {
                return json(['success' => 0, 'msg' => '推荐人不存在']);
            }

            if (UserModel::get(['username' => $input['username']])) {
                return json(['success' => 0, 'msg' => '用户名被占用']);
            }

            if (UserModel::get(['mobile' => $input['mobile']])) {
                return json(['success' => 0, 'msg' => '手机号被占用']);
            }

            $input['status']      = 1;
            $input['create_time'] = time();
            $input['invite'] ? $input['invite'] : Session::get('invite_id');
            $User = UserModel::create($input);
            if ($User->id) {
                $User->password = md5(md5($User->id . $input['password']));
                $User->save();
                Session::set('__token__', null);
                Hook::listen('user_register', $User); //用户注册成功钩子
                return json(['success' => 1, 'msg' => '注册成功', 'url' => url('index/user/login')]);
            }
        } else {
            $pathStr  = $this->request->path();
            $pathArr  = explode('/', $pathStr);
            $inviteId = isset($pathArr[1]) ? $pathArr[1] : null;
            if (is_numeric($inviteId) && !strpos($inviteId, ".")) {
                if (UserModel::get($inviteId)) {
                    Session::set('invite_id', $inviteId); //保存邀请人ID
                    $this->assign('invite_id', $inviteId);
                }
            }
            if (Session::has('user')) {
                $this->redirect(url('index/user/index'));
            }
            return $this->fetch();
        }
    }

    //用户登录
    public function login()
    {
        if ($this->request->isAjax()) {
            $input = $this->request->post();

            if (!captcha_check($input['code'])) {
                return json(['success' => 0, 'msg' => '验证码错误']);
            }

            if ($this->verifyToken($input['__token__']) === false) {
                return json(['success' => 0, 'msg' => '令牌错误']);
            }

            $User = UserModel::get(['username|mobile' => $input['username']]);
            if (is_null($User)) {
                return json(['success' => 0, 'msg' => '用户不存在']);
            }

            if (!$User->status) {
                return json(['success' => 0, 'msg' => '你的帐号被冻结']);
            }

            $password = md5(md5($User->id . $input['password']));
            if ($User->password != $password) {
                return json(['success' => 0, 'msg' => '登录密码错误']);
            }

            $User->login_time = time();
            $User->save();

            Session::set('user', array(
                'user_id'    => $User->id,
                'username'   => $User->username,
                'mobile'     => $User->mobile,
                'nickname'   => $User->nickname,
                'agent'      => $User->agent,
                'login_time' => $User->login_time,
            ));

            Hook::listen('user_login', $User); //用户登录成功钩子

            return json(['success' => 1, 'msg' => '登录成功', 'url' => url('index/user/index')]);
        } else {
            if (Session::has('user')) {
                $this->redirect(url('index/user/index'));
            }
            return $this->fetch();
        }
    }

    //退出登录
    public function logout()
    {
        Session::set('user', null);
        $this->redirect(url('index/user/login'));
    }

    //用户基本信息
    public function info()
    {
        if ($this->request->isAjax()) {
            $input = $this->request->post();

            if ($this->verifyToken($input['__token__']) === false) {
                return json(['success' => 0, 'msg' => '令牌错误']);
            }
            unset($input['__token__']);
            if (UserModel::update($input)) {
                return json(['success' => 1, 'msg' => '操作成功']);
            }
            return json(['success' => 0, 'msg' => '操作失败']);
        } else {
            $user_id = Session::get('user.user_id');
            $user    = UserModel::get($user_id);
            $this->assign('user', $user);
            return $this->fetch();
        }
    }

    //邀请好友
    public function invite()
    {
        $user_id = Session::get('user.user_id');
        $invites = Db::name('user')->field('username,qq,wechat,create_time')->where('invite', $user_id)->select();
        $this->assign('invites', $invites);
        return $this->fetch();
    }

    //用户充值
    public function recharge()
    {
        if ($this->request->isPost()) {
            $currency = config('currency');
            $post     = $this->request->post();
            if (!isset($post['uid']) || !isset($post['num'])) {
                return json(['status' => 0, 'msg' => '非法操作']);
            }
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['status' => 0, 'msg' => '支付密码错误']);
            }
            $user = Db::name('user')->find($post['uid']);
            if (!$user) {
                return json(['status' => 0, 'msg' => '代理不存在']);
            }
            if (strpos($post['num'], '.') !== false) {
                return json(['success' => 0, 'msg' => '请输入一个整数']);
            }
            if ($currency['minRecharge'] > 0) {
                if ($post['num'] < $currency['minRecharge']) {
                    return json(['success' => 0, 'msg' => '最低充值' . $currency['minRecharge'] . '个' . $currency['recharge']]);
                }
            }
            $result = Db::name('recharge')->insert([
                'user_id'     => $this->user['id'],
                'username'    => $this->user['username'],
                'agent_id'    => $user['id'],
                'num'         => $post['num'],
                'create_time' => time(),
            ]);
            if ($result) {
                return json(['success' => 1, 'msg' => '创建充值成功，请尽快支付给代理', 'url' => url('index/agent/record')]);
            }
            return json(['success' => 0, 'msg' => '操作失败']);
        }
    }

    //删除一条消息
    public function delMsg()
    {
        $id = intval($this->request->post('id'));
        if (!$id) {
            return json(['success' => 0, 'msg' => '非法操作']);
        }
        $result = Db::name('user_msg')
            ->where('id', $id)
            ->update(['is_delete' => 1, 'delete_time' => time()]);
        if (!$result) {
            return json(['success' => 0, 'msg' => '操作失败']);
        }
        return json(['success' => 1, 'msg' => '操作成功']);
    }

    //提现
    public function withdraw()
    {
        $config = config('withdraw');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            //判断是否开启提现
            if(!isset($config['withdrawSwitch'])){
                return json(['success' => 0, 'msg' => '暂未开放提现']);
            }
            //判断是否是提现时间
            $startHour   = $config['withdrawStime'];
            $endHour     = $config['withdrawEtime'];
            $currentHour = date('H', time());
            if ($currentHour < $startHour || $currentHour > $endHour) {
                return json(['success' => 0, 'msg' => '开放提现时间为每日' . $startHour . '-' . $endHour . '点']);
            }
            //判断是否满足直推人数
            if ($config['withdrawNum']) {
                $result = Db::name('user')->field('count(invite) as inviteNum')->where('invite', $this->user['id'])->find();
                if (!$result || $result['inviteNum'] < $config['withdrawNum']) {
                    return json(['success' => 0, 'msg' => '直推好友满' . $config['withdrawNum'] . '人允许提现']);
                }
            }
            //判断提现方式是否填写
            if ($post['type'] == 0 && empty($this->user['alipay'])) {
                return json(['success' => 0, 'msg' => '请先完善支付宝账号信息', 'url' => '/user/info']);
            }
            if ($post['type'] == 1 && empty($this->user['bank_card'])) {
                return json(['success' => 0, 'msg' => '请先完善银行账号信息', 'url' => '/user/info']);
            }
            //判断是否为空
            if (empty($post['money'])) {
                return json(['success' => 0, 'msg' => '请输入提现金额']);
            }
            //判断最低提现金额
            if ($post['money'] < $config['minWithdraw']) {
                return json(['success' => 0, 'msg' => '最低提现金额不能小于' . $config['minWithdraw'] . '元']);
            }
            //判断最高提现金额
            if ($post['money'] > $config['maxWithdraw']) {
                return json(['success' => 0, 'msg' => '最高提现金额不能大于' . $config['maxWithdraw'] . '元']);
            }
            //提现短信验证
            if ($post['money'] > $config['smsAmount']) {
                if (Session::get('mobile_code') != $post['code']) {
                    return json(['success' => 0, 'msg' => '短信验证码错误']);
                }
            }
            //判断余额
            if ($this->user['money'] < $post['money']) {
                return json(['success' => 0, 'msg' => '可提现余额不足']);
            }
            $message = "申请提现支出 {$post['money']} 元";
            $result  = dec_money($this->user['id'], $this->user['username'], 'money', $post['money'], $message, 7);
            if (!$result) {
                return json(['success' => 0, 'msg' => '提现失败，请重试']);
            }
            //计算手续费
            $fee = sprintf("%.2f", $config['withdrawFee'] / 100 * $post['money']);
            //计算购物币
            $shopping = sprintf("%.2f", $config['shopping'] / 100 * ($post['money'] - $fee));
            //计算实付金额
            $paid = sprintf("%.2f", $post['money'] - $fee - $shopping);
            //添加提现记录
            Db::name('withdraw')->insert([
                'user_id'     => $this->user['id'],
                'username'    => $this->user['username'],
                'money'       => $post['money'],
                'type'        => $post['type'] ? 'bank' : 'alipay',
                'fee'         => $fee,
                'paid'        => $paid,
                'shopping'    => $shopping,
                'note'        => $post['note'],
                'create_time' => time(),
            ]);
            return json(['success' => 1, 'msg' => '申请提现成功，等待管理员审核', 'url' => '/user']);
        } else {
            $this->setPayPwd($this->request->url(true));
            $this->assign('config', $config);
            return $this->fetch();
        }
    }

    //我的提现记录
    public function myWithdraw()
    {
        $list = Db::name('withdraw')->where('user_id', $this->user['id'])->order('id desc')->paginate(10);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //转账
    public function transfer()
    {
        $currency = config('currency');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($currency['isTransfer'])) {
                return json(['success' => 0, 'msg' => '转账功能未开放']);
            }
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            if (empty($post['money'])) {
                return json(['success' => 0, 'msg' => '请输入转账金额']);
            }
            if ($currency['minTransfer'] > 0) {
                if ($post['money'] < $currency['minTransfer']) {
                    return json(['success' => 0, 'msg' => '最低充值金额不能小于' . $currency['minTransfer']]);
                }
            }
            $payee = []; //收款人
            //转账给自己
            if ($post['mode'] == 0) {
                //不允许充值币转充值币
                if ($post['type'] == 0) {
                    return json(['success' => 0, 'msg' => '转账给自己，不允许' . $currency['recharge'] . '转' . $currency['recharge']]);
                }
                $payee['id']       = $this->user['id'];
                $payee['username'] = $this->user['username'];
            }
            //转账给别人
            if ($post['mode'] == 1) {
                if (empty($post['account'])) {
                    return json(['success' => 0, 'msg' => '收款人不能为空']);
                }
                $user = Db::name('user')->where('username|mobile', $post['account'])->find();
                if (!$user || $user['status'] == 0) {
                    return json(['success' => 0, 'msg' => '收款人不存在或被锁定']);
                }
                $payee['id']       = $user['id'];
                $payee['username'] = $user['username'];
            }
            //判断余额
            if ($post['type'] == 0 || $post['type'] == 1 || $post['type'] == 2) {
                if ($this->user['recharge'] < $post['money']) {
                    return json(['success' => 0, 'msg' => $currency['recharge'] . '余额不足']);
                }
            } elseif ($post['type'] == 3 || $post['type'] == 4 || $post['type'] == 5) {
                if ($this->user['money'] < $post['money']) {
                    return json(['success' => 0, 'msg' => $currency['money'] . '余额不足']);
                }
            }
            //开始转账
            switch ($post['type']) {
                case '0':
                    $message = "即时转账给 {$payee['username']} {$post['money']} {$currency['recharge']}";
                    dec_money($this->user['id'], $this->user['username'], 'recharge', $post['money'], $message, 8);
                    $message = "{$this->user['username']} 即时转账收入 {$post['money']} {$currency['recharge']}";
                    inc_money($payee['id'], $payee['username'], 'recharge', $post['money'], $message, 8);
                    break;
                case '1':
                    $message = "即时转账给 {$payee['username']} {$post['money']} {$currency['game']}";
                    dec_money($this->user['id'], $this->user['username'], 'recharge', $post['money'], $message, 8);
                    $message = "{$this->user['username']} 即时转账收入 {$post['money']} {$currency['game']}";
                    inc_money($payee['id'], $payee['username'], 'game', $post['money'], $message, 8);
                    break;
                case '2':
                    $message = "即时转账给 {$payee['username']} {$post['money']} {$currency['shopping']}";
                    dec_money($this->user['id'], $this->user['username'], 'recharge', $post['money'], $message, 8);
                    $message = "{$this->user['username']} 即时转账收入 {$post['money']} {$currency['shopping']}";
                    inc_money($payee['id'], $payee['username'], 'shopping', $post['money'], $message, 8);
                    break;
                case '3':
                    $message = "即时转账给 {$payee['username']} {$post['money']} {$currency['recharge']}";
                    dec_money($this->user['id'], $this->user['username'], 'money', $post['money'], $message, 8);
                    $message = "{$this->user['username']} 即时转账收入 {$post['money']} {$currency['recharge']}";
                    inc_money($payee['id'], $payee['username'], 'recharge', $post['money'], $message, 8);
                    break;
                case '4':
                    $message = "即时转账给 {$payee['username']} {$post['money']} {$currency['game']}";
                    dec_money($this->user['id'], $this->user['username'], 'money', $post['money'], $message, 8);
                    $message = "{$this->user['username']} 即时转账收入 {$post['money']} {$currency['game']}";
                    inc_money($payee['id'], $payee['username'], 'game', $post['money'], $message, 8);
                    break;
                case '5':
                    $message = "即时转账给 {$payee['username']} {$post['money']} {$currency['shopping']}";
                    dec_money($this->user['id'], $this->user['username'], 'money', $post['money'], $message, 8);
                    $message = "{$this->user['username']} 即时转账收入 {$post['money']} {$currency['shopping']}";
                    inc_money($payee['id'], $payee['username'], 'shopping', $post['money'], $message, 8);
                    break;
                default:
                    return json(['success' => 0, 'msg' => '非法操作']);
                    break;
            }
            return json(['success' => 1, 'msg' => '转账成功', 'url' => '/account/record?type=0']);
        } else {
            $this->setPayPwd($this->request->url(true));
            $this->assign('currency', $currency);
            return $this->fetch();
        }
    }

    //验证支付密码
    public function checkPwd()
    {
        if ($this->request->isPost()){
            if (!Session::has('user')) {
                return json(['success'=>0,'msg'=>'请先登录','url'=>'/login.html']);
            }
            $pwd = md5(md5($this->user['id'].$this->request->post('pwd')));
            if($pwd != $this->user['password2']){
                return json(['success'=>0,'msg'=>'支付密码错误']);
            }else{
                return json(['success'=>1,'msg'=>'通过支付密码验证']);
            }
        }
    }

    //设置支付密码
    public function pwd($id, $jump = '')
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if ($post['user_id'] != $this->user['id']) {
                return json(['success' => 0, 'msg' => '非法操作！']);
            }
            if ($post['password2'] != $post['password3']) {
                return json(['success' => 0, 'msg' => '确认支付密码和支付密码不一致']);
            }
            if ($post['password'] == $post['password2']) {
                return json(['success' => 0, 'msg' => '支付密码不能和登录密码一致']);
            }

            $password  = md5(md5($this->user['id'] . $post['password'])); //登录密码
            $password1 = md5(md5($this->user['id'] . $post['password1'])); //原来的支付密码
            $password2 = md5(md5($this->user['id'] . $post['password2'])); //新的支付密码

            if ($this->user['password'] != $password) {
                return json(['success' => 0, 'msg' => '登录密码错误']);
            }

            if (!empty($this->user['password2'])) {
                if (empty($post['password1'])) {
                    return json(['success' => 0, 'msg' => '请输入原支付密码']);
                }
                if ($this->user['password2'] != $password1) {
                    return json(['success' => 0, 'msg' => '原支付密码错误']);
                }
            }

            if (!Db::name('user')->where('id', $this->user['id'])->setField('password2', $password2)) {
                return json(['success' => 0, 'msg' => '设置支付密码失败']);
            }
            return json(['success' => 1, 'msg' => '设置支付密码成功','url'=>urldecode($jump)]);
        } else {
            $this->assign('user_id', $id);
            return $this->fetch();
        }

    }

    //我的钱包页面
    public function wallet(){
        return $this->fetch();
    }

    //发现页面
    public function find(){
        return $this->fetch();
    }
}
